package cn.yy.cloudpay.usb;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.android.usbport.ModbusTransfer;

import org.apache.log4j.Logger;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.HashMap;

import cn.yy.cloudpay.R;
import cn.yy.cloudpay.application.CloudPayApplication;
import cn.yy.cloudpay.cardread.FeixiScanT2Activity;
import cn.yy.cloudpay.common.iface.ResultVo;
import cn.yy.cloudpay.util.Constant;
import cn.yy.cloudpay.util.SerialUtils;
import cn.yy.cloudpay.util.StringUtil;

/**
 * Created by Administrator on 2018/1/27.
 */

public class ComUtil_N {
    public Logger log= Logger.getLogger(this.getClass());
    private Context mContext;
    private FeixiScanT2Activity activity;
    private CloudPayApplication mApplication;
    private int l=6;
    private int m=6;
    private int other=3;
    private String redaddr = "026E";
//    private String redaddr = "0004";
    private String redaddr_1 = "026F";
    private String redaddr_2 = "0270";
    private String redaddr_3 = "0271";
    private String redaddr_4 = "0272";
    private String redaddr_5 = "0273";
    private String redaddr_6 = "0274";

    public static int write_1 = 414; //开机
    public static int write_2 = 416;//停机
    private String warn_msg="";
    private String is_sms = "0";
    private int from;
    private static ComUtil_N comm;

    public static ComUtil_N instance(Context context){
        if(comm==null){
            comm = new ComUtil_N(context);
        }
        comm.l = 6;
        comm.m = 6;
        return comm;
    }

    private ComUtil_N(Context context){
        this.mContext = context;
        this.activity = (FeixiScanT2Activity)mContext;
        mApplication = (CloudPayApplication) activity.getApplication();
    }

    public void init(){
        activity.startin = 300;//等待进车，5分钟
        activity.startwin = 600;//等待指令，10分钟
        activity.startix = 600;//等待指令，10分钟
        activity.stopix = 20;   //停机 20 秒内
        activity.is_send_statrt = false;
        activity.is_send = true;
        activity.isCheck = true;
        sendStatus(-1,false,"");
    }
    //检测是否可以支付
    public void checkPay(final int f){
        from = f;
        log.info("===开始是否可以支付");
        try {
            init();
            final byte[] ret = ModbusTransfer.getInstance(mContext).readDataFromPlc(
                    Integer.parseInt("1"),
                    StringUtil.hexStr2Bytes(redaddr.trim()),
                    Integer.parseInt("1"),
                    3000);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (ret != null) {
                        try {
                            log.info("checkPay 读取成功");
                            String rs = StringUtil.byte2HexStr(ret);
                            log.info("获取字节：" + rs);
                            int equiment = Integer.parseInt(rs,16);
                            if (equiment == 7||equiment == 8) {
                                log.info(rs + ":待机中 打开扫描支付");
                                activity.setEquiment(equiment);
                                if(from==1){
                                    activity.sendPay();
                                }else{
                                    activity.openBankcard();
                                }
                            } else {
                                log.info(rs + ":设备正在使用中，请稍候再支付");
                                activity.playBeepSoundAndVibrate(R.raw.f2);
                                activity.getStatesStr().setText("设备状态:"+equiment+" 非停机状态");
                                activity.startScannerHandler("设备状态:"+equiment+" 非停机状态");
                            }
                        } catch (Exception ex) {
                            log.error("checkPay 异常" + ex);
                            restartCheckPay(0);
                        }
                    } else {
                        restartCheckPay(0);
                    }
                }
            });
        }catch (Exception ex){
            log.error("checkPay-send 异常"+ex);
            restartCheckPay(1);
        }
    }

    private void restartCheckPay(int i){
        l--;
        if(l>=0){
            log.info(redaddr+":检测是否可以支付"+l);
            if(i==1){
                activity.display(redaddr+":检测是否可以支付"+l);
            }else{
                activity.getStatesStr().setText(redaddr+":检测是否可以支付"+l);
            }
            checkPay(from);
        }else{
            log.info(redaddr+":检测完成");
            activity.startScannerHandler("检测是否可以支付，读取数据失败");
            activity.playBeepSoundAndVibrate(R.raw.f1);
        }
    }

    //发送启动设备指令
    public void startup(final int key){
        log.info("===开始发送指令");
        try {
            String adr = SerialUtils.readAddr(key);
            String data = SerialUtils.readData(1);
            final byte[] ret = ModbusTransfer.getInstance(mContext).sendCmdToPlc(
                    Integer.parseInt("1"),
                    StringUtil.hexStr2Bytes(adr),
                    StringUtil.hexStr2Bytes(data));
            final String result = ret==null? "指令发送失败！" : "指令发送成功："+ StringUtil.byte2HexStr(ret);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    activity.isCheck = false;
                    activity.stopCheck();
                    if(ret==null&&m>=0){
                        restartup(key,0);
                    }else if(ret!=null){
                        log.info(result+","+key);
                        activity.getStatesStr().setText("指令发送成功:"+key);
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        activity.isCheck = true;
                        activity.checkState();
                    }else{
                        log.info(key+":指令发送失败");
                        activity.getStatesStr().setText("指令发送失败");
                        activity.startScannerHandler("指令发送失败");
                        activity.playBeepSoundAndVibrate(R.raw.f1);
                    }
                }
            });
        }catch(Exception ex){
            log.error("startup-send 异常"+ex);
            restartup(key,1);
        }
    }

    public void restartup(int key,int i){
        m--;
        log.info(key+":指令发送失败 继续发送"+m);
        if(i==1){
            activity.display("指令发送失败 继续发送"+m);
        }else{
            activity.getStatesStr().setText("指令发送失败 继续发送"+m);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        startup(key);
    }

    //实时检测状态
    public void checkState(){
        try {
            if(!activity.isCheck){
                return;
            }
            final byte[] ret = ModbusTransfer.getInstance(mContext).readDataFromPlc(
                    Integer.parseInt("1"),
                    StringUtil.hexStr2Bytes(redaddr.trim()),
                    Integer.parseInt("1"),
                    1000);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(ret != null) {
                        try{
                            String rs = StringUtil.byte2HexStr(ret);
                            log.info("获取字节："+rs);
                            int equiment = Integer.parseInt(rs,16);

                            //上次警告，已停机，等待处理
                             if(equiment==9){
                                log.info("等待远程指令，并获取警告信息 "+activity.startix);
                                activity.getStatesStr().setText("等待远程指令，并获取警告信息");
                                activity.setEquiment(equiment);
                                checkControll();
                                 //收远程数据 5 分钟
                                activity.startix--;
                                if(activity.startix<1){
                                     log.info("未接收到指令，洗车完成，结束");
                                     activity.stopCheck();
                                    activity.playBeepSoundAndVibrate(R.raw.done);
                                     activity.startScannerHandler("未接收到指令，洗车完成，结束");
                                }
                                sendStatus(equiment,true);
                                if(activity.is_send){  //发送提示
                                    is_sms = "1";
                                    activity.is_send = false;
                                }
                                 activity.is_send_statrt = true;
                                other = 3;
                                checkOthers();
                                return;
                             }else if(activity.is_send_statrt){
                                 activity.setEquiment(equiment);
                                 if(equiment!=7&&equiment!=9&&equiment!=8){
                                     activity.is_send_statrt = false;
                                 }
                                 checkControll();
                                 if(!activity.is_send_statrt){
                                     return;
                                 }

                                 log.info(rs + ":等待远程指令。"+activity.startwin);
                                 activity.getStatesStr().setText("等待远程指令 状态："+equiment);
                                 activity.startwin--; //等待3分钟
                                 if(activity.startwin<1){
                                     log.info("未接收到指令，洗车完成，结束");
                                     activity.playBeepSoundAndVibrate(R.raw.done);
                                     activity.startScannerHandler("未接收到指令，洗车完成，结束");
                                     activity.stopCheck();
                                 }
                                 sendStatus(equiment,true);
                                 return;

                             }else if(activity.getEquiment()==7&&equiment==7){
                                 activity.setEquiment(equiment);
                                 checkControll();
                                 log.info(rs + ":等待进车。 "+activity.startin);
                                 activity.getStatesStr().setText("等待进车 状态："+equiment);
                                 activity.startin--; //等待3分钟
                                 if(activity.startin==100){
                                     activity.playBeepSoundAndVibrate(R.raw.nocar);
                                 }
                                 if(activity.startin<1){
                                     log.info("未进车，洗车完成，结束");
                                     activity.playBeepSoundAndVibrate(R.raw.f7);
                                     activity.startScannerHandler("未进车，洗车完成，结束");
                                     activity.stopCheck();
                                 }
                                 activity.is_send_statrt = false;
                                 activity.is_send = true;
                                 sendStatus(equiment,true);
                                 return;
                             }else if((equiment==1||equiment==7)){
                                log.info("洗车完成，结束");
                                 activity.playBeepSoundAndVibrate(R.raw.done);
                                activity.stopCheck();
                                activity.startScannerHandler("洗车完成，结束 状态："+equiment);
                                activity.setEquiment(equiment);
                                 activity.is_send_statrt = false;
                                 activity.is_send = true;
                                sendStatus(equiment,true);
                            } else if(equiment!=7){
                                log.info(rs + ":启动成功，正在运行 状态："+equiment);
                                activity.getStatesStr().setText("启动成功，正在运行 状态："+equiment);
                                activity.setEquiment(equiment);
                                 activity.is_send_statrt = false;
                                 activity.is_send = true;
                                sendStatus(equiment,true);
                            }
                            activity.ix = 20;
                            activity.stopix = 20;
                        }catch (Exception ex){
                            log.error("checkState 异常"+ex);
                            activity.stopCheck();
                            activity.startScannerHandler("状态检测异常");
                            activity.playBeepSoundAndVibrate(R.raw.f1);
                            activity.is_send_statrt = false;
                            activity.is_send = true;
                        }
                    }else{
                        recheckState(0);
                    }
                }
            });
        }catch (Exception ex){
            log.error("checkState-send 异常"+ex);
            recheckState(1);
        }
    }

    public void recheckState(int i){
        activity.ix--;
        if(activity.ix<1){
            activity.stopCheck();
            activity.startScannerHandler("检测状态,读取数据失败");
            return;
        }
        log.info(redaddr+":检测状态,读取数据失败 "+activity.ix);
        if(i==1){
            activity.display("检测状态,读取数据失败:"+activity.ix);
        }else {
            activity.getStatesStr().setText("检测状态,读取数据失败:"+activity.ix);
        }
    }

    private void checkOthers(){
        activity.isCheck = false;
        log.error("检查状态开始："+redaddr_1);
        checkOther(redaddr_1,false);
    }

    //检测其他状态
    public void checkOther(final String addr,final boolean ck){
        try {
            final byte[] ret = ModbusTransfer.getInstance(mContext).readDataFromPlc(
                    Integer.parseInt("1"),
                    StringUtil.hexStr2Bytes(addr.trim()),
                    Integer.parseInt("1"),
                    3000);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (ret != null) {
                        try {
                            log.info("checkOther 读取成功");
                            String rs = StringUtil.byte2HexStr(ret);
                            log.info("获取字节：" + rs);
                            int equiment = Integer.parseInt(rs,16);
                            if(addr.equals(redaddr_1)){
                                String msg = getMsg(redaddr_1,equiment);
                                warn_msg = "623_"+equiment+":"+msg;
                                checkOther(redaddr_2,false);
                            }
                            if(addr.equals(redaddr_2)){
                                String msg = getMsg(redaddr_2,equiment);
                                warn_msg += ",624_"+equiment+":"+msg;
                                checkOther(redaddr_3,false);
                            }
                            if(addr.equals(redaddr_3)){
                                String msg = getMsg(redaddr_3,equiment);
                                warn_msg += ",625_"+equiment+":"+msg;
                                checkOther(redaddr_4,false);
                            }
                            if(addr.equals(redaddr_4)){
                                String msg = getMsg(redaddr_4,equiment);
                                warn_msg += ",626_"+equiment+":"+msg;
                                checkOther(redaddr_5,false);
                            }
                            if(addr.equals(redaddr_5)){
                                String msg = getMsg(redaddr_5,equiment);
                                warn_msg += ",627_"+equiment+":"+msg;
                                activity.isCheck = true;
                                sendStatus(9,true,warn_msg);
                                activity.getTv_activity_warn().setText(warn_msg);
                                log.error("检查状态结束："+redaddr_5);
                                return;
                            }
                        } catch (Exception ex) {
                            log.error("checkOther 异常,重新检测" + ex);
                            recheckother();
                        }
                    }else{
                     recheckother();
                  }
                }
            });
        }catch (Exception ex){
            log.error("checkOther 异常"+ex);
            activity.isCheck = true;
            activity.is_send = true;
        }
    }

    private void recheckother(){
        if(other>0){
            other--;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            checkOthers();
        }else{
            activity.isCheck = true;
        }
    }


    //检测其他状态
    public void checkControll(){
        try {
            final byte[] ret = ModbusTransfer.getInstance(mContext).readDataFromPlc(
                    Integer.parseInt("1"),
                    StringUtil.hexStr2Bytes(redaddr_6.trim()),
                    Integer.parseInt("1"),
                    3000);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (ret != null) {
                        try {
                            log.info("checkControll 读取成功");
                            String rs = StringUtil.byte2HexStr(ret);
                            log.info("获取字节：" + rs);
                            int equiment = Integer.parseInt(rs,16);
                            if(equiment==1){
                                log.info("现场操作");
                                activity.stopCheck();
                                activity.startScannerHandler("现场操作 628状态："+equiment);
                                activity.is_send_statrt = false;
                                activity.is_send = true;
                                sendStatus(25,false);
                            }
                        } catch (Exception ex) {
                            log.error("checkControll 异常,重新检测" + ex);
                        }
                    }
                }
            });
        }catch (Exception ex){
            log.error("checkControll 异常"+ex);
        }
    }

    public void sendStatus(int status,final boolean isSend) {
        is_sms = "0";
        sendStatus(status,isSend,"");
    }

    public void sendStatus(int status,final boolean isSend,String warn_msg) {
        try {
            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("posNum", CloudPayApplication.deviceSN);
            params.put("status", status);
            params.put("warn_msg",warn_msg);
            params.put("isSend", is_sms);

            RequestParams params2 = httParams(Constant.EQUMENT_INFO, params);
            x.http().post(params2, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String arg0) {
                    is_sms = "0";
                    ResultVo rv = JSON.parseObject(arg0, ResultVo.class);
                    Object params = rv.getReturnParams();
                    if ("0".equals(rv.getReturnCode()) && params != null) {
                        if ("2".equals(params.toString())&&isSend) {
                            activity.is_send_statrt = false;
                            log.info("后台发送启动指令");
                            activity.getTv_command().setText("后台发送启动指令");
                            startup(write_1);
                        }
                        if ("3".equals(params.toString())&&isSend) {
                            activity.is_send_statrt = true;
                            log.info("后台发送回复指令");
                            activity.getTv_command().setText("后台发送回复指令");
                            startup(write_2);
                        }
                        if ("4".equals(params.toString())&&isSend) {
                            activity.getTv_command().setText("后台发送完成指令");
                            startup(write_2);
                            activity.is_send_statrt = false;
                            activity.is_send = true;
                            log.info("后台结束洗车");
                            activity.startScannerHandler("后台结束洗车");
                            activity.stopCheck();
                            sendStatus(24,false);
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    log.error("请求失败", ex);
                }

                @Override
                public void onFinished() {
                    is_sms = "0";
                }

                @Override
                public void onCancelled(CancelledException arg0) {
                }
            });
        }catch (Exception ex){
            log.error("请求异常",ex);
        }
    }

    public RequestParams httParams(String serviceId,HashMap<String, Object> params){
        String paramStr = JSON.toJSONString(params);
        String rs = "{\"serviceId\":\""+serviceId+"\",\"params\":"
                + paramStr + "}";
        activity.getTv_activity_warn().setText("状态接收："+mApplication.getServiceAddress());
        RequestParams params2 = new RequestParams(mApplication.getServiceAddress());
        params2.setConnectTimeout(3000);
        params2.setMaxRetryCount(0);
        params2.setCacheMaxAge(0);
        params2.setBodyContent(rs);
        return params2;
    }

    public String getMsg(String addr,int state){
        if(redaddr_1.equals(addr)){
            if(state==1){
                return "停车到位";
            }else{
                return "";
            }
        }
        if(redaddr_2.equals(addr)){
            if(state==1){
                return "天车原点限位";
            }else{
                return "";
            }
        }
        if(redaddr_3.equals(addr)){
            if(state==1){
                return "天车后限位";
            }else{
                return "";
            }
        }
        if(redaddr_4.equals(addr)){
            if(state==1){
                return "天车不在原点位";
            }else if(state==2){
                return "停车不到位";
            }else{
                return "";
            }
        }
        if(redaddr_5.equals(addr)){
            if(state==1){
                return "回原点完成";
            }else if(state == 2){
                return "自动回原点中";
            }else if(state == 3){
                return "支付成功";
            }else if(state == 4){
                return "已启动";
            }else{
                return "";
            }
        }
        return "";
    }
}
